<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>WebSocket 客户端</title>
<style>
  body {font-family: Arial, sans-serif; padding: 20px;}
  #gameBoard {display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; gap: 20px;}
  .playerArea {border: 2px solid #888; padding: 10px; border-radius: 10px; height: 200px; background-color: #f9f9f9; overflow-y: auto;}
  .playerArea h3 {margin-top: 0;}
  #controls {margin-top: 20px;}
  #inputMessage {width: 70%; padding: 10px; margin-right: 10px;}
  #sendButton {padding: 10px 20px;}
  .log {font-size: 14px; color: #333;}
  .self {color: blue; }
  .server {color: green; }
</style>
</head>
<body>
  <h2>WebSocket 客户端</h2>
  <div id="gameBoard">
    <div class="playerArea" id="player1"><h3>玩家1</h3><div class="log" id="log1"></div></div>
    <div class="playerArea" id="player2"><h3>玩家2</h3><div class="log" id="log2"></div></div>
    <div class="playerArea" id="player3"><h3>玩家3</h3><div class="log" id="log3"></div></div>
    <div class="playerArea" id="player4"><h3>玩家4</h3><div class="log" id="log4"></div></div>
  </div>
  <div id="controls">
    <input type="text" id="inputMessage" placeholder="Type a message..." />
    <button id="sendButton">Send</button>
  </div>
  <script>
    // 端口设置
    const socket = new WebSocket('ws://localhost:8080/ws');
    // 心跳间隔（毫秒）
    const HEARTBEAT_INTERVAL = 2000; // 30秒
    // 心跳时间
    let heartbeatTimer;
    // 最后服务器返回的心跳时间
    let lastPongTime = Date.now();
    
    socket.onopen = function () {
      console.log('链接成功!');
      // 启动心跳
      startHeartbeat();
      // 发送游戏基本信息
      document.getElementById('sendButton').disabled = false;
      const message = {
        type: 1,
        openId: 'person1',
        online: true,
        status: 1,
        data: {type: 1, time: Date.now()}
      };
      socket.send(JSON.stringify(message));
    };

    socket.onmessage = function (event) {
      const msg = JSON.parse(event.data);
      if (msg.type === 'PONG') {
        lastPongTime = Date.now(); // 更新最后一次 Pong 时间
        console.log('收到 Pong 响应');
      } else {
        console.log('收到消息:', msg);
      }
    };

    socket.onclose = function () {
      console.log('链接关闭');
      // 清除心跳
      clearInterval(heartbeatTimer);
    };
    socket.onerror = function (error) {
      console.error('error: ', error);
    };
		// 发送游戏消息
    document.getElementById('sendButton').addEventListener('click', function () {
      const inputMessage = document.getElementById('inputMessage').value;
      if (inputMessage) {
        // 假设玩家1发送（可通过下拉选玩家ID）
        const message = JSON.stringify({ player: 1, msg: inputMessage });
        socket.send(message);

        const log = document.getElementById('log1');
        const p = document.createElement('p');
        p.classList.add('self');
        p.textContent = `You: ${inputMessage}`;
        log.appendChild(p);
        log.scrollTop = log.scrollHeight;

        document.getElementById('inputMessage').value = '';
      }
    });

    // 启动心跳
    function startHeartbeat() {
      heartbeatTimer = setInterval(() => {
        if (socket.readyState === WebSocket.OPEN) {
          // 发送心跳
          console.log(JSON.stringify({ DataType: 100, time: Date.now() }));
          socket.send(JSON.stringify({ DataType: 100, time: Date.now() }));
          // 检查心跳（例如 40 秒无响应则断开）
          if (Date.now() - lastPongTime > 40000) {
            console.error('心跳超时，服务器无响应');
            socket.close();
          }
        }
      }, HEARTBEAT_INTERVAL);
    }
  </script>
</body>
</html>